﻿<%@ WebHandler Language="C#" Class="publicHouse" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Chenxin.Lib.Utility;
using System.Data;
using System.Data.OleDb;

public class publicHouse : AjaxHandlerBase
{
    public publicHouse()
    {
        htTypePermit.Add("add", Constants.Permit_PublicHouseAdd);
        htTypePermit.Add("fileupload", Constants.Permit_PublicHouseDel);
        htTypePermit.Add("deletelist", Constants.Permit_PublicHouseUpLoad);
    }
    
    //*******************************************
    //功能概要       ：重写的请求处理方法
    //参数説明       ：context 请求的上下文
    //返回值説明     ：无
    //功能詳細       ：父类中隐藏了IHttpHandler接口方法，本类中须对本方法进行重写
    //作成者         ：chenyg
    //作成日         ：2010-05-04 
    //*******************************************
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "add":
                strResponse = add(context);
                break;
            case "deletelist":
                strResponse = del(context);
                break;
            case "getlist":
                strResponse = GetList(context);
                break;
            case "checkroom":
                CheckRoom(context);
                break;
            case "loadcommunity":
                LoadCommunity(context);
                break;
            case "getcommunityinfo":
                LoadCommunityById(context);
                break;
            case "fileupload":
                FileUpload(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    //返回值説明     ：void
    //功能詳細       ：删除
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string del(HttpContext context)
    {
        try
        {
            //转换成实体
            string Id = context.Request["modelid"];
            if (string.IsNullOrEmpty(Id))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "标识丢失，请联系管理员！");
            string[] delist = Id.Split(',');
            for (int i = 0; i < delist.Length; i++)
            {
                Guid tempId = new Guid(delist[i]);
                Chenxin.Lib.House.DAL.House_PublicDatum.Delete(tempId);
            }
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "删除成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }

    //*******************************************
    //功能概要       ：添加资料盘
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：添加资料盘
    //作成者         ：chenyg
    //作成日         ：2010-03-03
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string add(HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.House_PublicDatum model = (Chenxin.Lib.House.Entity.House_PublicDatum)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_PublicDatum));
            model.HouseId = Guid.NewGuid();
            model.Adddate = DateTime.Now;
            model.AddDepart = CurrentUserInfo.DepartName;
            model.AddDepartId = CurrentUserInfo.DepartId;
            model.AddPerson = CurrentUserInfo.UserName;
            model.AddPersonId = CurrentUserInfo.UserId;
            model.IsTransformed = false;
            model.CompanyId = CurrentUserInfo.CompanyId;
            model.CompanyName = CurrentUserInfo.CompanyName;
            Chenxin.Lib.House.DAL.House_PublicDatum.Add(model);
            
            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            //跟单方式
            house_TraceInfo.TraceType = 0;
            //跟单内容	 
            house_TraceInfo.TraceContext = CurrentUserInfo.UserName + "添加了资料盘。";
            //房源Id	 
            house_TraceInfo.HouseId = model.HouseId;
            //房源编号	
            house_TraceInfo.HouseCode = "";
            //房源地址	 
            house_TraceInfo.HouseAddress = model.HouseAddress;
            house_TraceInfo.status = 0;

            house_TraceInfo.OprDepart = model.AddDepart;
            house_TraceInfo.OprDepartId = model.AddDepartId;
            house_TraceInfo.OprPerson = model.AddPerson;
            house_TraceInfo.OprPersonId = model.AddPersonId;
            
            AddTrace(house_TraceInfo);
            
            return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "添加成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
        }
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetList(HttpContext context)
    {
        string community = context.Request["community"];
        string region = context.Request["region"];
        string block = context.Request["block"];
        string houseuse = context.Request["houseuse"];
        string buildingtype = context.Request["buildingtype"];
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        
        int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1:int.Parse(context.Request["pageindex"]) +1;//页码
        int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30:int.Parse(context.Request["pagesize"]);//页记录数

        System.Text.StringBuilder sb = new StringBuilder();
        
        sb.Append(" (1=1) ");
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_PublicHouse_ViewAll))
        {}
        
        //判断级联菜单
        if (departs != Guid.Empty)
            sb.AppendFormat(" and (AddDepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据失败");

            sb.AppendFormat(" and (AddDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.AppendFormat(" and CompanyId = '{0}'", company);
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_PublicHouse_ViewCity))
        {
            sb.Append("and EXISTS(");
            sb.Append("Select 1 from v_Hr_User_BaseInfo M ");
            sb.AppendFormat("WHERE House_PublicDatum.AddPersonId = M.Userid AND  M.CityId= '{0}' ", CurrentUserInfo.CityId);
            sb.Append(")");
        }
        else
        {
            sb.AppendFormat(" and CompanyId = '{0}'", CurrentUserInfo.CompanyId);
        }
        
        ////查看公司房源权限
        //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_PublicHouse_ViewCompany))
        //{
        //    sb.Append("EXISTS(");
        //    sb.Append("Select 1 from v_Hr_User_BaseInfo M ");
        //    sb.AppendFormat("WHERE House_PublicDatum.AddPersonId = M.Userid AND  M.CompanyId= '{0}' ", CurrentUserInfo.CompanyId);
        //    sb.Append(")");
        //}  else
        //{
        //    sb.Append(" (1 <> 1) ");
        //}
        
        if (!string.IsNullOrEmpty(community))
            sb.AppendFormat(" AND (community LIKE '%{0}%')", community);
        if (!string.IsNullOrEmpty(region))
            sb.AppendFormat(" AND (region LIKE '%{0}%')", region);
        if (!string.IsNullOrEmpty(block))
            sb.AppendFormat(" AND (block LIKE '%{0}%')", block);
        if (!string.IsNullOrEmpty(houseuse))
            sb.AppendFormat(" AND (houseuse LIKE '%{0}%')", houseuse);
        if (!string.IsNullOrEmpty(buildingtype))
            sb.AppendFormat(" AND (buildingtype LIKE '%{0}%')", buildingtype);
       
        StringBuilder sbOrder = new StringBuilder();
        sbOrder.Append(" Adddate DESC ");
        System.Data.DataSet dslist = null;
        string fieldlist = "*";
        string tablefieldlist = "*";

        dslist = Chenxin.Lib.House.DAL.House_PublicDatum.GetList(
                iPageIndex, iPageSize, sbOrder.ToString(), "House_PublicDatum", sb.ToString(), fieldlist, tablefieldlist, true);

        int count = (int)dslist.Tables[1].Rows[0][0];

        string strHtml = "";
        if (!GetListHtml(dslist, out strHtml))
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
        }

        dslist.Dispose();
        dslist = null;
        return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
    }

    private bool GetListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr><th width=\"40\" ><a name=\"del\" class=\"check_all\" href=\"#\">全选</a></th>");
        sb.Append("<th width=\"30\">区域</th>");
        sb.Append("<th width=\"100\" >楼盘/门号/房号</th>");
        sb.Append("<th width=\"60\">固话/手机</th>");
        sb.Append("<th width=\"60\">客户姓名</th>");
        sb.Append("<th width=\"50\">面积</th>");
        sb.Append("<th width=\"60\">类型</th>");
        sb.Append("<th width=\"50\">是否转换</th>");
        sb.Append("<th width=\"50\">添加时间</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");
        int i = 0;
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            if (i % 2 == 0)
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_favorlist\">", row["HouseId"].ToString());
            else
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist bluebgcolor\">", row["HouseId"].ToString());
            //操作列
            if (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsTransformed", false))
                sb.AppendFormat("<td>{0}</td>", string.Format("<input name=\"delList\" type=\"checkbox\" value=\"{0}\" /><a name=\"link\"  class=\"a_already_transformed\">转盘</a>", row["HouseId"].ToString(), row["CommunityId"].ToString()));
            else
                sb.AppendFormat("<td>{0}</td>", string.Format("<input name=\"delList\" type=\"checkbox\" value=\"{0}\" /><a name=\"link\" href=\"HouseBaseInfoAdd.aspx?id={1}&houseid={2}\" class=\"a_transformed\">转盘</a>", row["HouseId"].ToString(), row["CommunityId"].ToString(), row["HouseId"].ToString()));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Region", ""));
            string strHouse = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Community", "") + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingName", "") + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Room", "");
            sb.AppendFormat("<td>{0}</td>", strHouse);
            string tel =  Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Phone", "-") + "/" + Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Mobile", "-");
            sb.AppendFormat("<td>{0}</td>", tel);
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingArea", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingType", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsTransformed", false) ? "已转":"未转");
            sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Adddate", DateTime.Today));
            sb.Append("</tr>");

            i++;
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }

    /// <summary>
    /// 根据拼音字母或者文字，查询符合条件的楼盘
    /// </summary>
    /// <param name="context"></param>
    private void LoadCommunity(HttpContext context)
    {
        Guid departId = CurrentUserInfo.DepartId;
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, departId);
        Chenxin.Lib.House.Entity.House_BusinessSetting setting = null;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        setting = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            setting = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(departId);
            if (setting != null) cs.Set(strCachKey, setting);
        }

        string strCitys = "";

        if (setting != null)
        {
            if (!string.IsNullOrEmpty(setting.CanAddAtCityId)) strCitys = setting.CanAddAtCityId;
        }

        if (strCitys == "") strCitys = CurrentUserInfo.CityId.ToString();

        System.Text.StringBuilder sbwhere = new System.Text.StringBuilder();
        string[] aryCity = strCitys.Split(new char[] { ',' });
        foreach (string strCityId in aryCity)
        {
            if (string.IsNullOrEmpty(strCityId)) continue;
            if (sbwhere.Length == 0)
                sbwhere.AppendFormat("((CityId = '{0}')", strCityId);
            else
                sbwhere.AppendFormat(" OR (CityId = '{0}')", strCityId);
        }
        sbwhere.Append(")");

        if (context.Request["query"] != null)
        {
            sbwhere.AppendFormat(" AND (CommunityName like '%{0}%' OR Py like '%{0}%')", context.Request["query"]);

            System.Data.DataTable dt = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(sbwhere.ToString()).Tables[0];

            System.Text.StringBuilder sugestionSb = new System.Text.StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                sugestionSb.AppendFormat("'{0}',", dr["CommunityName"]);
            }
            context.Response.Write(string.Format("{{query:'{0}',suggestions:[{1}],{2}}}", context.Request["query"], sugestionSb.Length > 0 ? sugestionSb.Remove(sugestionSb.Length - 1, 1).ToString() : sugestionSb.ToString(), JsonHelp.Convert2Json(dt).Replace("\"rows\"", "data")));
        }
    }

    /// <summary>
    /// 根据拼音字母或者文字，查询符合条件的楼盘
    /// </summary>
    /// <param name="context"></param>
    private void LoadCommunityById(HttpContext context)
    {
        Guid departId = CurrentUserInfo.DepartId;
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, departId);
        Chenxin.Lib.House.Entity.House_BusinessSetting setting = null;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        setting = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            setting = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(departId);
            if (setting != null) cs.Set(strCachKey, setting);
        }

        string strCitys = "";

        if (setting != null)
        {
            if (!string.IsNullOrEmpty(setting.CanAddAtCityId)) strCitys = setting.CanAddAtCityId;
        }

        if (strCitys == "") strCitys = CurrentUserInfo.CityId.ToString();

        System.Text.StringBuilder sbwhere = new System.Text.StringBuilder();
        string[] aryCity = strCitys.Split(new char[] { ',' });
        foreach (string strCityId in aryCity)
        {
            if (string.IsNullOrEmpty(strCityId)) continue;
            if (sbwhere.Length == 0)
                sbwhere.AppendFormat("((CityId = '{0}')", strCityId);
            else
                sbwhere.AppendFormat(" OR (CityId = '{0}')", strCityId);
        }
        sbwhere.Append(")");

        Chenxin.Lib.House.Entity.Community_BaseInfo community_BaseInfo = null;
        Chenxin.Lib.House.Entity.House_PublicDatum house_PublicDatum = null;
        if (context.Request["modelid"] != null)
        {
            sbwhere.AppendFormat(" AND (CommunityId ='{0}')", context.Request["modelid"]);

            community_BaseInfo = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(new Guid(context.Request["modelid"]));
        }
        if (context.Request["houseid"] != null)
        {
           house_PublicDatum = Chenxin.Lib.House.DAL.House_PublicDatum.GetModel(new Guid(context.Request["houseid"]));
        }
        context.Response.Write(string.Format("{{success:'1',msg:'',data:{{comminity:{0},house:{1}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(community_BaseInfo), Chenxin.Lib.Utility.JsonHelp.Convert2Json(house_PublicDatum)));
       
    }
    
    /// <summary>
    /// 验证房间号
    /// </summary>
    /// <param name="context"></param>
    private void CheckRoom(HttpContext context)
    {
        try
        {
            if (context.Request["communityid"] != null && context.Request["buildingid"] != null && context.Request["room"] != null)
            {
                string where = string.Format(" CommunityId='{0}' and BuildingId='{1}' and Room='{2}' and CompanyId='{3}'", context.Request["communityid"], context.Request["communityid"], context.Request["communityid"], CurrentUserInfo.CompanyId);

                if (Chenxin.Lib.House.DAL.House_BaseInfo.Exists(where))
                {
                    context.Response.Write("{success:1,msg:'',data:{exist:true}}");
                }
                else
                {
                    context.Response.Write("{success:1,msg:'',data:{exist:false}}");
                }
            }
            else
            {
                context.Response.Write("{success:1,msg:'',data:{exist:true}}");
            }
        }
        catch (Exception e)
        {
            context.Response.Write("{success:1,msg:'',data:{exist:true}}");
        }
    }


    //*******************************************
    //功能概要       ：批量添加资料盘
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：添加资料盘
    //作成者         ：chenyg
    //作成日         ：2010-03-03
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string addbat(string FileName, HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.House_PublicDatum model = null;
            DataSet dsExcel = new DataSet();
            DataTable dt = new DataTable();
            string SheetName = "house";
            string strXls = FileName.Substring(FileName.LastIndexOf(".") + 1).ToLower();
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + context.Server.MapPath(FileName) + ";Extended Properties=Excel 8.0";
            OleDbConnection oleConn = new OleDbConnection(strConn);
            oleConn.Open();
            OleDbCommand myOleDbCommand = new OleDbCommand("select * from [" + SheetName + "$]", oleConn);
            OleDbDataAdapter dataAda = new OleDbDataAdapter(myOleDbCommand);
            oleConn.Close();
            dsExcel = new DataSet();
            dataAda.Fill(dsExcel, "[" + SheetName + "$]");
            dt = dsExcel.Tables[0];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                model = new Chenxin.Lib.House.Entity.House_PublicDatum();
                model.HouseId = Guid.NewGuid();
                model.Adddate = DateTime.Now;
                model.AddDepart = CurrentUserInfo.DepartName;
                model.AddDepartId = CurrentUserInfo.DepartId;
                model.AddPerson = CurrentUserInfo.UserName;
                model.AddPersonId = CurrentUserInfo.UserId;
                model.IsTransformed = false;
                model.CompanyId = CurrentUserInfo.CompanyId;
                model.CompanyName = CurrentUserInfo.CompanyName;

                if (dt.Rows[i]["Community"] != null)
                {
                    string community = Convert.ToString(dt.Rows[i]["Community"]);
                    if (community.Length<1)
                        return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "第" + i + "行小区名称为空！");
                    model.Community = community.Length < 200 ? community : community.Substring(0, 200);
                }
                if (dt.Rows[i]["BuildingName"] != null)
                    model.BuildingName = Convert.ToString(dt.Rows[i]["BuildingName"]).Length < 100 ? Convert.ToString(dt.Rows[i]["BuildingName"]) : Convert.ToString(dt.Rows[i]["BuildingName"]).Substring(0,100);
                if (dt.Rows[i]["Region"] != null ) {
                    string region = Convert.ToString(dt.Rows[i]["Region"]);
                    if (region.Length<1)
                        return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "第" + i + "行区域为空！");
                    model.Region = region.Length < 50 ? region : region.Substring(0, 50);
                }
                if (dt.Rows[i]["Block"] != null)
                    model.Block = Convert.ToString(dt.Rows[i]["Block"]).Length < 50 ? Convert.ToString(dt.Rows[i]["Block"]) : Convert.ToString(dt.Rows[i]["Block"]).Substring(0,50);
                if (dt.Rows[i]["Room"] != null)
                    model.Room = Convert.ToString(dt.Rows[i]["Room"]).Length < 50 ? Convert.ToString(dt.Rows[i]["Room"]) : Convert.ToString(dt.Rows[i]["Room"]).Substring(0,50);
                if (dt.Rows[i]["HouseAddress"] != null)
                    model.HouseAddress = Convert.ToString(dt.Rows[i]["HouseAddress"]).Length < 200 ? Convert.ToString(dt.Rows[i]["HouseAddress"]) : Convert.ToString(dt.Rows[i]["HouseAddress"]).Substring(0,200);
                if (dt.Rows[i]["HouseUse"] != null)
                    model.HouseUse = Convert.ToString(dt.Rows[i]["HouseUse"]).Length < 100 ? Convert.ToString(dt.Rows[i]["HouseUse"]) : Convert.ToString(dt.Rows[i]["HouseUse"]).Substring(0,100);
                if (dt.Rows[i]["BuildingType"] != null)
                    model.BuildingType= Convert.ToString(dt.Rows[i]["BuildingType"]).Length < 100 ? Convert.ToString(dt.Rows[i]["BuildingType"]) : Convert.ToString(dt.Rows[i]["BuildingType"]).Substring(0,100);
                if (dt.Rows[i]["CustomerName"] != null)
                {
                    string customerName = Convert.ToString(dt.Rows[i]["CustomerName"]);
                    if (customerName.Length<1)
                        return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "第" + i + "行客户姓名为空！");
                    model.CustomerName = customerName.Length < 150 ? customerName : customerName.Substring(0, 150);
                }
                if (dt.Rows[i]["Mobile"] != null)
                    model.Mobile= Convert.ToString(dt.Rows[i]["Mobile"]).Length < 50 ? Convert.ToString(dt.Rows[i]["Mobile"]) :Convert.ToString(dt.Rows[i]["Mobile"]).Substring(0,50);
                if (dt.Rows[i]["Phone"] != null)
                    model.Phone= Convert.ToString(dt.Rows[i]["Phone"]).Length < 50 ? Convert.ToString(dt.Rows[i]["Phone"]) : Convert.ToString(dt.Rows[i]["Phone"]).Substring(0,50);
                if (dt.Rows[i]["Nationality"] != null)
                    model.Nationality = Convert.ToString(dt.Rows[i]["Nationality"]).Length < 20 ? Convert.ToString(dt.Rows[i]["Nationality"]) : Convert.ToString(dt.Rows[i]["Nationality"]).Substring(0,20);
                if (dt.Rows[i]["AddressZip"] != null)
                    model.AddressZip = Convert.ToString(dt.Rows[i]["AddressZip"]).Length < 20 ? Convert.ToString(dt.Rows[i]["AddressZip"]) : Convert.ToString(dt.Rows[i]["AddressZip"]).Substring(0,50);
                if (dt.Rows[i]["District"] != null)
                    model.District = Convert.ToString(dt.Rows[i]["District"]).Length < 200 ? Convert.ToString(dt.Rows[i]["District"]) : Convert.ToString(dt.Rows[i]["District"]).Substring(0,200);
                if (dt.Rows[i]["BuildingArea"] != null)
                    try
                    {
                        model.BuildingArea = Convert.ToDecimal(dt.Rows[i]["BuildingArea"]);
                    }
                    catch (Exception e) {
                        return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "第" + i + "行面积不对！");
                    }
                
               Chenxin.Lib.House.DAL.House_PublicDatum.Add(model);
            }  
          
            return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "添加成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
        }
    }

    /// <summary>
    /// 普通文件文件
    /// </summary>
    /// <param name="context"></param>
    private void FileUpload(HttpContext context)
    {
        try
        {
            HttpPostedFile file = context.Request.Files["FileData"];
            string localPath = System.Configuration.ConfigurationManager.AppSettings["FilePath"] + "File/";

            string savePath = context.Server.MapPath(localPath);
            string fileName = Guid.NewGuid().ToString("N") + file.FileName.Substring(file.FileName.LastIndexOf('.'));
            string subName = file.FileName.Substring(file.FileName.LastIndexOf('.')+1);
            if (!("xls".Equals(subName) || "xlsx".Equals(subName)))
            {
                context.Response.Write("{success:0,msg:'文件格式不正确！',data:''}");
                return;
            }
            if (file != null)
            {
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }

                file.SaveAs(savePath + fileName);

                context.Response.Write(string.Format("{{success:1,msg:'文件上传成功！',data:{{filepath:'{0}'}}}}", localPath + fileName));
            }
            else
            {
                context.Response.Write("{success:0,msg:'文件上传失败！',data:''}");
            }

            addbat(localPath + fileName,context);
        }
        catch (Exception e)
        {
            context.Response.Write("{success:0,msg:'文件上传失败！',data:''}");
        }
    }


}